package com.soundShape.utils
{
	
	
	import com.soundShape.events.SoundShapeEvent;
	import com.soundShape.mediators.photos.PhotosMediator;
	import com.soundShape.model.ApplicationModel;
	
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.events.KeyboardEvent;
	import flash.filesystem.File;
	import flash.ui.Keyboard;
	
	import flashx.textLayout.events.DamageEvent;
	
	import mx.managers.PopUpManager;

	public class ImageMaster
	{
		[Inject]
		public var photosMediator:PhotosMediator;
		
		[Dispatcher]
		public var dispatcher:IEventDispatcher;
		
		[Inject]
		public var applicationModel:ApplicationModel;
		
		private const MAX_FILES:uint = 200;
		
		private var targetVolume:File;
		private var fileList:Array;
		
		public function ImageMaster()
		{
		}
		
		[EventHandler(event="SoundShapeEvent.OPEN_FILE_BROWSER")]
		public function openFileBrowser():void 
		{
			var homeDir:File = File.userDirectory;
			homeDir.addEventListener(Event.SELECT, directorySelected);
			homeDir.browseForDirectory("Choose a folder to open");
		}
		

		
		private function directorySelected(e:Event):void
		{
			this.targetVolume = e.target as File;
			this.iterateFiles(this.targetVolume);
			
			photosMediator.view.swfLdrProgress.visible = true;
		}
		
		private function iterateFiles(dir:File):void
		{
			if (!dir.isDirectory || dir.isHidden || !dir.exists || dir.name.search(/^\..*$/) != -1) return;
			
			var listing:Array = dir.getDirectoryListing();
			
			this.fileList = [];
			
			for each(var f:File in listing)
			{
				if (this.fileList.length >= this.MAX_FILES) break;
				
				if (f.isHidden || !f.exists || f.name.search(/^\..*$/) != -1) continue;
				
				if (f.isDirectory)
				{
					this.iterateFiles(f);
				}
				else
				{
					if(isImageFile(f))
					{
						this.fileList.push(f);
					}
						
				}
			}
			
			var soundShapeEvent:SoundShapeEvent = new SoundShapeEvent(SoundShapeEvent.FILES_READY);
			soundShapeEvent.data = this.fileList;
			this.dispatcher.dispatchEvent(soundShapeEvent);
			
			// the target volume can be stored to expedite future file operations
			this.applicationModel.targetVolume = this.targetVolume;
			
		}
		
		private function isImageFile(file:File):Boolean
		{
			
			trace("file.extension.toLocaleLowerCase() " + file.extension.toLocaleLowerCase());
			
			if ((file.extension.toLocaleLowerCase() == "jpg" || file.extension.toLocaleLowerCase() == "jpeg" || file.extension.toLocaleLowerCase() == "png" || file.extension.toLocaleLowerCase() == "gif"))
			{
				return true;
			}
		return false;	
		}
		
		private function copyFiles(e:Event=null):void
		{
			
		}
	}
}